<template>
  <view class="repair-container">
    <!-- 维修项目 - 绿色背景标题栏 -->
    <view class="repair-header">
      <text>维修项目：{{formData.title}}</text>
    </view>

    <!-- 故障描述 -->
    <view class="fault-desc-section">
      <view class="section-label">故障描述</view>
      <view class="desc-input-wrap">
		<view class="base-label-box">
			<text class="label">请输入故障描述</text>
			<text class="required">*</text>
			<text class="fail-label" v-if="!formData.faultDesc && isSubmit">请输入故障描述</text>
		</view>
        <textarea 
          class="desc-textarea" 
          v-model="formData.faultDesc"
          placeholder="请输入备注说明"
          placeholder-style="color: #B5B5B5"
        />
      </view>
    </view>

    <!-- 基本信息 -->
    <view class="basic-info-section">
      <view class="section-label">基本信息</view>
      
      <!-- 故障部件 -->
      <view class="form-item">
		<view class="base-label-box">
			<text class="label">故障部件</text>
		</view>
        <input
          class="input" 
          type="text" 
          v-model="formData.faultPart" 
          placeholder="请输入故障部件"
          placeholder-style="color: #B5B5B5"
        />
      </view>

      <!-- 故障日期 -->
      <view class="form-item" @click="showDatePicker">
		<view class="base-label-box">
			<text class="label">故障日期</text>
			<text class="required">*</text>
			<text class="fail-label" v-if="!formData.faultDate && isSubmit">请选择故障日期</text>
		</view>
		
        <view class="picker-value" :class="{ active: !formData.faultDate && isSubmit }">
		   <text class= "placeholderText" v-if="!formData.faultDate">请选择故障日期</text>
           <text v-else>{{ formData.faultDate}}</text>
           <image class="arrow" src="/static/my/my-right.png" mode="aspectFit"></image>
        </view>
      </view>

      <!-- 紧急程度 -->
      <view class="form-item">
	    <view class="base-label-box">
			<text class="label">紧急程度</text>
			<text class="required">*</text>
			<text class="fail-label" v-if="!formData.urgency && isSubmit">请选择紧急程度</text>
		</view>
		
        <view class="radio-group">
          <view 
            class="radio-btn" 
            :class="{ active: formData.urgency === 'normal' }"
            @click="formData.urgency = 'normal'"
          >一般</view>
          <view 
            class="radio-btn" 
            :class="{ active: formData.urgency === 'urgent' }"
            @click="formData.urgency = 'urgent'"
          >紧急</view>
        </view>
      </view>

      <!-- 预约时间 -->
      <view class="form-item" @click="showTimePicker">
		<view class="base-label-box">
			<text class="label">预约时间</text>
			<text class="required">*</text>
			<text class="fail-label" v-if="!formData.appointmentTime && isSubmit">请选择预约时间</text>
		</view>
        <view class="picker-value" :class="{ active: !formData.appointmentTime && isSubmit }">
			<text class= "placeholderText" v-if = "!formData.appointmentTime">请预约时间</text>
			<text v-else>{{ formData.appointmentTime}}</text>
           <image class="arrow" src="/static/my/my-right.png" mode="aspectFit"></image>
        </view>
      </view>

      <!-- 选择维修商 -->
      <view class="form-item">
		<view class="base-label-box">
         <text class="label">选择维修商</text>
		 <text class="required">*</text>
		 <text class="fail-label" v-if="!formData.repairer && isSubmit">请选择维修商</text>
		</view>
        <view class="picker-value" :class="{ active: !formData.repairer && isSubmit }">
		  <text class= "placeholderText" v-if = "!formData.repairer">选择维修商</text>
		  <text v-else>{{ formData.repairer}}</text>
           <image class="arrow" src="/static/my/my-right.png" mode="aspectFit"></image>
        </view>
      </view>
    </view>

    <!-- 附件信息 -->
    <view class="attachment-section">
      <view class="section-label">附件信息</view>
      <view class="upload-wrap">
        <view class="upload-label">
          请上传附件信息
          <text class="upload-desc">(支持图片和视频格式)</text>
        </view>
        <!-- 图片列表 -->
        <view class="image-list">
          <view  class="image-item" v-for="(item, index) in imageList" :key="index">
            <image :src="item.url" mode="aspectFill" @click="previewImage(index)"/>
            <text class="delete-icon" @click.stop="deleteImage(index)">×</text>
          </view>
          <!-- 上传按钮 -->
          <view class="upload-box" @click="chooseImage" v-if="imageList.length < 9">
            <text class="plus">+</text>
            <text class="upload-text">上传附件</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 提交按钮 -->
	<view class="button-section">
	  <button class="gvr-yellow-button submitbutton" @click="handleSubmit">提交工单</button>
	</view>

    <!-- 日期选择器 -->
    <service-work-picker
      ref="dateTimePicker"
      :title="timeType === 'fault' ? '选择故障日期' : '选择预约时间'"
	  :value="currentPickerValue"
      @confirm="handleDateConfirm"
    />
  </view>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
// 表单数据
const formData = ref({
  title: '',
  faultPart: '',
  faultDate: '',
  urgency: '',
  appointmentTime: '',
  repairer: '',
  faultDesc: ''
})
const isSubmit = ref(false)

// 紧急程度选项
const urgencyOptions = [
  { label: '一般', value: 'normal' },
  { label: '紧急', value: 'urgent' }
]

// 设置默认故障日期为今天
onMounted(() => {
  const now = new Date()
  
  formData.value.faultDate = formatDate(now)
  
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const { title, type } = currentPage.options
  // 判断是否是编辑模式
  if (type && title) {
	 formData.value.title = title  
  }
})

// 监听紧急程度变化
watch(() => formData.value.urgency, (newVal) => {
  if (newVal === 'urgent') {
    // 如果选择紧急，设置预约时间为2小时后
    const twoHoursLater = new Date()
    twoHoursLater.setHours(twoHoursLater.getHours() + 2)
    formData.value.appointmentTime = formatDate(twoHoursLater)
  } else {
    formData.value.appointmentTime = ''
  }
})

// 格式化日期
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  return `${year}年${month}月${day}日 ${hour}:00`
}

const dateTimePicker = ref(null)
const timeType = ref('') // 区分是故障日期还是预约时间

// 当前选择器的值
const currentPickerValue = ref('')

// 显示日期选择器
const showDatePicker = () => {
  timeType.value = 'fault'
  // 设置当前选择器的值为故障日期
  currentPickerValue.value = formData.value.faultDate || formatDate(new Date())
  console.log('设置的日期值：', currentPickerValue.value) // 调试日志
  dateTimePicker.value.open()
}

// 显示时间选择器
const showTimePicker = () => {
  
  timeType.value = 'appointment'
  // 设置当前选择器的值为预约时间
  currentPickerValue.value = formData.value.appointmentTime || formatDate(new Date())
  dateTimePicker.value.open()
}

// 日期确认回调
const handleDateConfirm = (date) => {
  if (timeType.value === 'fault') {
    formData.value.faultDate = date
  } else {
    formData.value.appointmentTime = date
  }
  // 清空当前选择器的值
  currentPickerValue.value = ''
}

// 处理文件上传
const handleUpload = () => {
  // uni.chooseImage({
  //   count: 9 - uploadList.value.length,
  //   success: (res) => {
  //     uploadList.value.push(...res.tempFilePaths.map(url => ({ url })))
  //   }
  // })
}

// 删除文件
const deleteFile = (index) => {
  uploadList.value.splice(index, 1)
}


// 提交表单
const handleSubmit = () => {
  isSubmit.value = true
  // 表单验证
  if (!formData.value.faultPart) {
    uni.showToast({ title: '请输入故障部件', icon: 'none' })
    return
  }
  if (!formData.value.faultDate) {
    uni.showToast({ title: '请选择故障日期', icon: 'none' })
    return
  }
  if (!formData.value.appointmentTime) {
    uni.showToast({ title: '请选择预约时间', icon: 'none' })
    return
  }
  if (!formData.value.repairer) {
    uni.showToast({ title: '请选择维修商', icon: 'none' })
    return
  }

  console.log('提交的表单数据：', formData.value)
  uni.showToast({
    title: '提交成功',
    icon: 'success'
  })
  uni.navigateTo({
    url: '/pages/service/repair-success'
  })
}

// 在script部分添加以下代码
const imageList = ref([])

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 9 - imageList.value.length,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      // 处理选择的图片
      const tempFiles = res.tempFilePaths.map(path => ({
        url: path,
        status: 'pending' // pending-待上传 uploading-上传中 success-成功 fail-失败
      }))
      imageList.value.push(...tempFiles)
      
      // 这里可以添加自动上传逻辑
      uploadImages(tempFiles)
    }
  })
}

// 预览图片
const previewImage = (index) => {
  const urls = imageList.value.map(item => item.url)
  uni.previewImage({
    urls,
    current: index
  })
}

// 删除图片
const deleteImage = (index) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这张图片吗？',
    success: (res) => {
      if (res.confirm) {
        imageList.value.splice(index, 1)
      }
    }
  })
}

// 上传图片
const uploadImages = async (files) => {
  for (let file of files) {
    try {
      file.status = 'uploading'
      // 这里添加实际的上传逻辑
      // const result = await uploadFile(file.url)
      // file.url = result.url // 更新为服务器返回的URL
      file.status = 'success'
    } catch (error) {
      file.status = 'fail'
      console.error('上传失败:', error)
    }
  }
}
</script>

<style lang="scss" scoped>
.repair-container {
  min-height: 100vh;
  background: #fff;
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

// 维修项目头部
.repair-header {
  display: flex;
  align-items: center;
  height: 74rpx;
  background: #719949;
  border: 1px solid rgba(228,228,228,1);
  padding: 14rpx 48rpx;
  font-family: PingFangSC-Medium;
  font-size: 32rpx;
  color: #FFFFFF;
  letter-spacing: 0;
  font-weight: 500;
}

// 故障描述区域
.fault-desc-section {
  padding:0 54rpx;
  padding-top: 38rpx;
  padding-bottom: 12rpx;
  
  .section-label {
    font-family: PingFangSC-Medium;
    font-size: 32rpx;
    color: #000000;
    letter-spacing: 0;
    font-weight: 500;
  }
  
  .desc-input-wrap {
	margin-left: 2rpx;
	margin-right: 2rpx;
	margin-top: 40rpx;
	
	.base-label-box {
	  display: flex;
	  align-items: center;
	  margin-bottom: 14rpx;
	  
	  .label {
	    font-family: PingFangSC-Medium;
	    font-size: 28rpx;
	    color: #000000;
	    letter-spacing: 0;
	    line-height: 20px;
	    font-weight: 500;
	  }
	  .required {
	    font-family: PingFangSC-Medium;
	    font-size: 28rpx;
	    color: #BA0C2F;
	    letter-spacing: 0;
	    line-height: 20px;
	    font-weight: 500;
	  }
	  .fail-label {
	    font-family: PingFangSC-Medium;
	    font-size: 24rpx;
	    color: #BA0C2F;
	    letter-spacing: 0;
	    font-weight: 500;
	    margin-left: 10rpx;
	  }
	}
  
    
    .desc-textarea {
	  margin-left: 2rpx;
      width: 100%;
      height: 190rpx;
      border: 2rpx solid rgba(0,30,50,1);
      padding: 20rpx;
      box-sizing: border-box;
	  
	  font-family: PingFangSC-Medium;
	  font-size: 28rpx;
	  color: #001E32;
	  letter-spacing: 0;
	  font-weight: 500;
      
      // &::placeholder {
      //   color: #B5B5B5;
      // }
    }
  }
}

// 基本信息区域
.basic-info-section {
  padding:0 54rpx;
  padding-top: 38rpx; 
  padding-bottom: 12rpx;
  
  .section-label {
    font-family: PingFangSC-Medium;
    font-size: 32rpx;
    color: #000000;
    letter-spacing: 0;
    font-weight: 500;
  }
}

// 表单��通用样式
.form-item {
  padding:0 2rpx;
  padding-top: 40rpx;
  
  .base-label-box {
    display: flex;
    align-items: center;
    margin-bottom: 26rpx;
    
    .label {
      font-family: PingFangSC-Medium;
      font-size: 28rpx;
      color: #000000;
      letter-spacing: 0;
      line-height: 20px;
      font-weight: 500;
    }
    .required {
      font-family: PingFangSC-Medium;
      font-size: 28rpx;
      color: #BA0C2F;
      letter-spacing: 0;
      line-height: 20px;
      font-weight: 500;
    }
    .fail-label {
      font-family: PingFangSC-Medium;
      font-size: 24rpx;
      color: #BA0C2F;
      letter-spacing: 0;
      font-weight: 500;
      margin-left: 10rpx;
     }
   }
  
  .input {
    width: 100%;
    height: 40rpx;
   
    font-family: PingFangSC-Medium;
    font-size: 28rpx;
    color: #001E32;
    letter-spacing: 0;
    font-weight: 500;
	padding-bottom: 13rpx;
    border-bottom: 2rpx solid rgba(0,30,50,1);
	
    // &::placeholder {
    //   color: #999999;
    // }
  }
  
  // 紧急程度单选按钮组
  .radio-group {
    display: flex;
    gap: 24rpx;
    
    .radio-btn {
	  display: flex;
	  align-items: center;
	  justify-content: center;
      width: 156rpx;
      height: 64rpx;
      text-align: center;
      font-family: PingFangSC-Medium;
      font-size: 28rpx;
      color: #000000;
      letter-spacing: 0;
      text-align: center;
      font-weight: 500;
      background: #DEDEDE;
      border-radius: 10rpx;
      
      &.active {
        background: #285789;
        color: #FFFFFF;
      }
    }
  }
  
  .picker-value {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 40rpx;
	padding-bottom: 13rpx;
    border-bottom: 2rpx solid rgba(0,30,50,1);
	
	font-family: PingFangSC-Medium;
	font-size: 28rpx;
	color: #001E32;
	letter-spacing: 0;
	font-weight: 500;
	
	.placeholderText {
		color: #B5B5B5;
	}
	
	&.active {
	 border-bottom: 2rpx solid #BA0C2F;	
	}


    .arrow {
	  margin-right: 10rpx;
      transform: rotate(90deg);
      width: 18rpx;
	  height: 32rpx;
    }
	
  }

}


// 附件信息区域
.attachment-section {
  padding:0 54rpx;
  padding-top: 38rpx; 
  padding-bottom: 12rpx;
  
  .section-label {
    font-family: PingFangSC-Medium;
    font-size: 32rpx;
    color: #000000;
    letter-spacing: 0;
    font-weight: 500;
  }
  
  .upload-wrap {
	 margin-top: 40rpx;
	 padding:0 2rpx;
	 margin-bottom: 14rpx;
    .upload-label {
      font-family: PingFangSC-Medium;
      font-size: 28rpx;
      color: #000000;
      letter-spacing: 0;
      line-height: 20px;
      font-weight: 500;
      
      .upload-desc {
        font-family: PingFangSC-Medium;
        font-size: 28rpx;
        color: #B5B5B5;
        letter-spacing: 0;
        line-height: 20px;
        font-weight: 500;
      }
    }
  
  
    .image-list {
	  display: grid;
	  grid-template-columns: repeat(3, 1fr);
	  gap: 30rpx;
	  padding: 5rpx;
	
	  .image-item {
	    position: relative;
	    width: 190rpx;
	    height: 190rpx;
	    overflow: hidden;
	    border: 2rpx solid #001E32;
	  
	    image {
		  width: 100%;
		  height: 100%;
		  object-fit: cover;
	    }
	  
	    .delete-icon {
		  top: 8rpx;
		  right: 8rpx;
		  width: 32rpx;
		  height: 32rpx;
		  background: rgba(0, 0, 0, 0.4);
		  color: #FFFFFF;
		  border-radius: 50%;
		  display: flex;
		  align-items: center;
		  justify-content: center;
		  font-size: 24rpx;
	    }
	  }
	  .upload-box {
	    width: 190rpx;
	    height: 190rpx;
	    border: 2rpx solid #001E32;
	    display: flex;
	    flex-direction: column;
	    align-items: center;
	    justify-content: center;
	  
	    .plus {
	      font-size: 70rpx;
		  color: #001E32;
		  line-height: 1;
		  margin-bottom: 16rpx;
	    }
	  
	    .upload-text {
		  font-family: PingFangSC-Regular;
		  font-size: 24rpx;
		  color: #B5B5B5;
		  letter-spacing: 0;
		  text-align: center;
		  font-weight: 400;
	    }
	  }
    }
  }
}


/* 日期选择器样式 */
.picker-wrapper {
  background: #FFFFFF;
  border-radius: 24rpx 24rpx 0 0;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #EEEEEE;
}

.picker-header text {
  font-size: 28rpx;
}

.picker-header text:first-child {
  color: #999999;
}

.picker-header text:last-child {
  color: #1890FF;
}

.picker-view {
  width: 100%;
  height: 480rpx;
}

.picker-item {
  line-height: 88rpx;
  text-align: center;
  font-size: 28rpx;
}


.button-section {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding-bottom: env(safe-area-inset-bottom);
  background-color: #FFFFFF;
}
.submitbutton {
  border-radius: 0;
}
</style> 
